package com.aidex.biz.service.impl;

import com.aidex.biz.domain.*;
import com.aidex.biz.domain.bo.PaymentScheduleDto;
import com.aidex.biz.domain.enums.CustomerEnum;
import com.aidex.biz.domain.enums.DongTaiTypeEnum;
import com.aidex.biz.mapper.CustomerMapper;
import com.aidex.biz.mapper.JinjianInfoMapper;
import com.aidex.biz.messageSend.MessageSendService;
import com.aidex.biz.service.*;
import com.aidex.biz.utils.hengchang.HengChangServer;
import com.aidex.common.annotation.DataScope;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.core.service.BaseServiceImpl;
import com.aidex.common.utils.NumberUtils;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.sql.SqlUtil;
import com.aidex.system.service.ISysUserService;
import com.aidex.system.service.SysDictDataService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 客户进件Service业务层处理
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2023-12-11
 */
@Service
@Transactional(readOnly = true)
public class JinjianInfoServiceImpl extends BaseServiceImpl<JinjianInfoMapper, JinjianInfo> implements JinjianInfoService {
    private static final Logger log = LoggerFactory.getLogger(JinjianInfoServiceImpl.class);

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private JinjianCodeService jinjianCodeService;
    @Autowired
    private ToHomeUserService toHomeUserService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CustomerDongtaiService customerDongtaiService;
    @Autowired
    private ZifangPushService zifangPushService;
    @Autowired
    private HengChangServer hengChangServer;
    @Autowired
    private CustomerXiezuService customerXiezuService;
    @Autowired
    private MessageSendService messageSendService;
    @Autowired
    private JinjianBillService jinjianBillService;
    @Autowired
    private CapBillService capBillService;
    @Autowired
    private LoanBillService loanBillService;
    @Autowired
    private LoanBillDetailService loanBillDetailService;

    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private ToHomeService toHomeService;
    @Autowired
    private XiansuoChengbenLogService xiansuoChengbenLogService;
    @Autowired
    private SysDictDataService sysDictDataService;

    /**
     * 获取单条数据
     *
     * @param jinjianInfo 客户进件
     * @return 客户进件
     */
    @Override
    public JinjianInfo get(JinjianInfo jinjianInfo) {
        JinjianInfo dto = super.get(jinjianInfo);
        return dto;
    }

    /**
     * 获取单条数据
     *
     * @param id 客户进件id
     * @return 客户进件
     */
    @Override
    public JinjianInfo get(String id) {
        JinjianInfo dto = super.get(id);
        return dto;
    }


    /**
     * 查询客户进件列表
     *
     * @param jinjianInfo 客户进件
     * @return 客户进件
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<JinjianInfo> findList(JinjianInfo jinjianInfo) {
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            jinjianInfo.setCompanyId(null);
        } else {
            jinjianInfo.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        return super.findList(jinjianInfo);
    }

    /**
     * 分页查询客户进件列表
     *
     * @param jinjianInfo 客户进件
     * @return 客户进件
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<JinjianInfo> findPage(JinjianInfo jinjianInfo) {
        return super.findPage(jinjianInfo);
    }

    /**
     * 保存客户进件
     *
     * @param jinjianInfo
     * @return 结果
     */
    @Override
    public boolean save(JinjianInfo jinjianInfo) {
        return super.save(jinjianInfo);
    }


    /**
     * 删除客户进件信息
     *
     * @param jinjianInfo
     * @return 结果
     */
    @Override
    public boolean remove(JinjianInfo jinjianInfo) {
        return super.remove(jinjianInfo);
    }

    /**
     * 批量删除客户进件
     *
     * @param ids 需要删除的客户进件ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteJinjianInfoByIds(String[] ids) {
        return mapper.deleteJinjianInfoByIds(ids);
    }

    /**
     * 获取最大编号
     *
     * @param jinjianInfo 客户进件
     * @return 结果
     */
    @Override
    public int findMaxSort(JinjianInfo jinjianInfo) {
        return NumberUtils.nextOrder(mapper.findMaxSort(jinjianInfo));
    }

    @Override
    public PageInfo<JinjianInfo> findMyList(JinjianInfo jinjianInfo) {
        PageDomain page = jinjianInfo.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(mapper.findList(jinjianInfo));
    }

    @Override
    public int pushZifang(String customerId, String type) {
        // 查询客户信息
        if (StringUtils.isNotNull(customerId)) {
            Customer customer = customerMapper.get(customerId);

        }
        return 0;
    }

    @Override
    public boolean add(JinjianInfo jinjianInfo) {
        Integer index = jinjianCodeService.findMaxSort(new JinjianCode());
        if (null == index) {
            index = 1;
        }
        String indeStr = "";
        if (index >= 10) {
            indeStr = "000" + index;
        } else {
            indeStr = "0000" + index;
        }
        if (index >= 100) {
            indeStr = "000" + index;
        }
        if (index >= 1000) {
            indeStr = "0" + index;
        }
        // 保存序号
        JinjianCode jinjianCode = new JinjianCode();
        jinjianCode.setSort(index);
        jinjianCodeService.save(jinjianCode);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        jinjianInfo.setId("CODE-" + simpleDateFormat.format(new Date()) + indeStr);
        jinjianInfo.setIsNewRecord();
        jinjianInfo.setAgreeServiceAmount("0");//默认同意
        jinjianInfo.setHetongQianshu("0");
        jinjianInfo.setServiceContractSign("0");
        jinjianInfo.setIsGps("0");
        jinjianInfo.setBeiyongKey("0");
        jinjianInfo.setDiyaSendOut("0");
        jinjianInfo.setDiyaSign("0");
        jinjianInfo.setCarInsurancePolicy("0");
        // 去掉预审步骤
        jinjianInfo.setStatus("1");
        jinjianInfo.setUpdateTime(new Date());
        //方案确认
        jinjianInfo.setJinjianStatus("0");

        // 记录谈单经理信息
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        if (null != currentUser) {
            jinjianInfo.setTandanUserId(currentUser.getId());
            jinjianInfo.setTandanUserName(currentUser.getName());
        }

        if (!StringUtils.isEmpty(jinjianInfo.getToHomeUserId())) {
            ToHomeUser toHomeUser = toHomeUserService.get(jinjianInfo.getToHomeUserId());
            if (null != toHomeUser) {
                toHomeUser.setYushenStatus("1");
                toHomeUser.setJinjianId(jinjianInfo.getId());
                toHomeUserService.save(toHomeUser);
                jinjianInfo.setLaiyuan(toHomeUser.getLaiyuan());
                ToHome toHome = toHomeService.get(toHomeUser.getTohomeId());
                if (null != toHome) {
                    // 进件的人员并不是业绩归属人员，需要将进件的用户信息改为邀约经理
                    jinjianInfo.setUserId(toHome.getUserId());
                    jinjianInfo.setUserName(toHome.getUserName());
                    jinjianInfo.setDeptId(toHome.getDeptId());
                    jinjianInfo.setDeptName(toHome.getDeptName());
                    jinjianInfo.setCompanyId(toHome.getCompanyId());
                    jinjianInfo.setCompanyName(toHome.getCompanyName());

                    jinjianInfo.setXscbLogId(toHome.getXscbLogId());
                }
            }
        }
        // 预审申请
        if (!StringUtils.isEmpty(jinjianInfo.getCustomerId())) {
            Customer customer = customerService.get(jinjianInfo.getCustomerId());
            if (null != customer) {
                customer.setBusinessStatus(CustomerEnum.CUS_YS.getStatus());
                customer.setAmount(jinjianInfo.getYxEdu().toString());
                customerService.save(customer);
            }
            // 资方进件
            if (StringUtils.isNotEmpty(jinjianInfo.getZifangType())) {
                if (null != customer) {
                    ZifangPush zifangPush = new ZifangPush();
                    zifangPush.setCustomerId(customer.getId());
                    zifangPush.setQudaoType(jinjianInfo.getZifangType());
                    zifangPush.setCusName(customer.getCusName());
                    zifangPush.setCusPhone(customer.getPhone());
                    customer.setZiFangPushId(jinjianInfo.getId());
                    zifangPush.setAmount(customer.getAmount());
                    zifangPush.setId(jinjianInfo.getId());
                    zifangPush.setIsNewRecord();
                    if (zifangPushService.save(zifangPush)) {
                        JSONObject jsonObject = hengChangServer.synChannelCustomerInfo(customer);
                        if (200 == jsonObject.getIntValue("code")) {
                            // 撞库成功后进行推送
                            zifangPush.setStatus("0");
                            zifangPush.setRemark("恒昌-推送成功！");
                        } else {
                            zifangPush.setStatus("1");
                            if (null != jsonObject.getJSONObject("data") && jsonObject.getJSONObject("data").containsKey("msg")) {
                                zifangPush.setRemark(jsonObject.getJSONObject("data").getString("msg"));
                            } else {
                                zifangPush.setRemark("恒昌-推送失败！");
                            }

                        }
                        zifangPush.setNewRecord(false);
                        zifangPushService.save(zifangPush);
                    }
                }
            }
        }

        CustomerDongtai customerDongtai = new CustomerDongtai();
        customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
        customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
        ;
        customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-进件方案确认"
                + (StringUtils.isNotEmpty(jinjianInfo.getZifangType()) ? jinjianInfo.getZifangType() : ""));
        customerDongtaiService.save(customerDongtai);

        // 方案确认@所有人
//        String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//        messageSendService.sendJinjianVxNewsToCompany(null, "方案确认", new String[]{jinjianInfo.getCustomerName(), sdf});

        return this.save(jinjianInfo);
    }

    @Override
    public boolean edit(JinjianInfo jinjianInfo) {
        return this.save(jinjianInfo);
    }


    @Override
    public boolean updateBizJinjianInfoShenHe(JinjianInfo jinjianInfo) {
        if (null != jinjianInfo) {
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            String operate = "";
            if ("5".equals(jinjianInfo.getJinjianStatus())) {
                operate = "通过";
                this.changeToHomeByJinjian(jinjianInfo, "3");
            } else if ("-5".equals(jinjianInfo.getJinjianStatus())) {
                operate = "驳回";
                // 驳回后退回到客户进件 重新方案确认
                this.changeToHomeByJinjian(jinjianInfo, "0");
            }

            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-进件审批（" + operate + "）");
            customerDongtaiService.save(customerDongtai);

            // 进件审批@销售
//            SysUser user = iSysUserService.get(jinjianInfo.getUserId());
//            String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//            messageSendService.sendJinjianVxNewsToCompany(user, "进件审批", new String[]{jinjianInfo.getCustomerName(), operate, sdf});

            return this.edit(jinjianInfo);
        }
        return false;
    }


    @Override
    public boolean updateBizJinjianInfoQianYue(JinjianInfo jinjianInfo) {
        if (null != jinjianInfo) {
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-客户签约");
            customerDongtaiService.save(customerDongtai);
            ToHomeUser toHomeUser = this.changeToHomeByJinjian(jinjianInfo, "4");
            jinjianInfo.setQiandanTime(new Date());

            // 签约@销售
            SysUser user = iSysUserService.get(jinjianInfo.getUserId());
            String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            String toHomeCompanyId = null;
            if (null != toHomeUser) {
                ToHome toHome = toHomeService.get(toHomeUser.getTohomeId());
                toHomeCompanyId = toHome.getToHomeCompanyId();
            }
            if (StringUtils.isNull(toHomeCompanyId)) {
                toHomeCompanyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
            }
            messageSendService.sendJinjianVxNewsToCompany(new String[]{user.getPhonenumber()}, "客户签约", new String[]{jinjianInfo.getCustomerName(), sdf}, toHomeCompanyId);

            return this.edit(jinjianInfo);
        }
        return false;
    }

    @Override
    public boolean updateBizJinjianInfoQingKuan(JinjianInfo jinjianInfo) {
        if (null != jinjianInfo) {
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-请款");
            customerDongtaiService.save(customerDongtai);
            return this.edit(jinjianInfo);
        }
        return false;
    }

    @Override
    public boolean updateBizJinjianInfoFk(JinjianInfo jinjianInfo) {
        if (null != jinjianInfo) {
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-客户放款");
            customerDongtaiService.save(customerDongtai);
            jinjianInfo.setIsFk("1");
            jinjianInfo.setCjTime(new Date());

            // 放款后生成还款信息
            LoanBill loanBill = new LoanBill();
            String uuid = UUID.randomUUID().toString();
            loanBill.setId(uuid);
            loanBill.setIsNewRecord();
            loanBill.setJinjianId(jinjianInfo.getId());
            loanBill.setUserId(jinjianInfo.getUserId());
            loanBill.setUserName(jinjianInfo.getUserName());
            loanBill.setDeptId(jinjianInfo.getDeptId());
            loanBill.setDeptName(jinjianInfo.getDeptName());
            loanBill.setCustomerId(jinjianInfo.getCustomerId());
            loanBill.setCusName(jinjianInfo.getCustomerName());
            loanBill.setCompanyId(jinjianInfo.getCompanyId());
            loanBill.setLoanType(jinjianInfo.getBackType());
            loanBill.setLv(jinjianInfo.getLv());
            loanBill.setMonths(jinjianInfo.getFenqiTime());
            loanBill.setPrincipal(jinjianInfo.getSjEdu());
            loanBill.setMonthPayment(jinjianInfo.getMonthlyPayment());
            loanBill.setTotalPayment(jinjianInfo.getTotalPayment());
            loanBill.setTotalInterest(jinjianInfo.getTotalInterest());

            loanBill.setIsOverdue(0);
            loanBill.setIsPayAll(0);

            //计算还款日 当月放款，下个月开始还款

            Date fkTime = jinjianInfo.getFkTime();
            LocalDateTime localDateTime = fkTime.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime();

            LocalDateTime currentMonthHkTime = localDateTime.withDayOfMonth(jinjianInfo.getMonthlyPayDate());
            Date firstHkTime = Date.from(currentMonthHkTime.plusMonths(1).atZone(ZoneId.systemDefault()).toInstant());
            Date lastHkTime = Date.from(currentMonthHkTime.plusMonths(jinjianInfo.getFenqiTime()).atZone(ZoneId.systemDefault()).toInstant());
            loanBill.setPayDate(firstHkTime);
            loanBill.setBeginTime(firstHkTime);
            loanBill.setEndTime(lastHkTime);
            loanBillService.save(loanBill);
            // 明细表
            List<LoanBillDetail> loanBillDetailList = new ArrayList<>();
            LoanBillDetail loanBillDetail = null;
            for (PaymentScheduleDto dto : jinjianInfo.getPaymentSchedule()) {
                loanBillDetail = new LoanBillDetail();
                loanBillDetail.setUserId(jinjianInfo.getUserId());
                loanBillDetail.setUserName(jinjianInfo.getUserName());
                loanBillDetail.setDeptId(jinjianInfo.getDeptId());
                loanBillDetail.setDeptName(jinjianInfo.getDeptName());
                loanBillDetail.setCompanyId(jinjianInfo.getCompanyId());
                loanBillDetail.setLoanId(uuid);
                loanBillDetail.setPeriod(dto.getPeriod());
                loanBillDetail.setInterest(dto.getInterest());
                loanBillDetail.setMonthPayment(dto.getPayment());
                loanBillDetail.setPrincipal(dto.getPrincipal());
                loanBillDetail.setRemainingPrincipal(dto.getRemaining());
                loanBillDetail.setIsOverdue(0);
                Date hkDate = Date.from(currentMonthHkTime.plusMonths(dto.getPeriod()).atZone(ZoneId.systemDefault()).toInstant());
                loanBillDetail.setPayDate(hkDate);
                loanBillDetail.preInsert();
                loanBillDetailList.add(loanBillDetail);
            }
            loanBillDetailService.insertBatch(loanBillDetailList);

            // 放款默认成交
            Customer customer = customerService.get(jinjianInfo.getCustomerId());
            if (!CustomerEnum.CHENG_JIAO.getStatus().equals(customer.getStatus())) {

                // 签约后自动变更为成交客户
                customer.setBusinessStatus(CustomerEnum.CHENG_JIAO.getStatus());
                customer.setStatus(CustomerEnum.CHENG_JIAO.getStatus());
                customer.setIsCj(1);
                customer.setCjTime(new Date());
                customerService.save(customer);
                // 成交后取消协助
                CustomerXiezu customerXiezu = new CustomerXiezu();
                customerXiezu.setCustomerId(jinjianInfo.getCustomerId());
                customerXiezuService.deleteByCustomerId(customerXiezu);

                customerDongtai = new CustomerDongtai();
                customerDongtai.setCustomerId(customer.getId());
                customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-客户成交");
                customerDongtaiService.save(customerDongtai);
            }

            // 放款时更新线索成本记录表
            String xscbLogId = this.jinjianCleaning(jinjianInfo);
            if (StringUtils.isNotNull(xscbLogId)) {
                jinjianInfo.setXscbLogId(xscbLogId);
            }
            return this.edit(jinjianInfo);
        }
        return false;
    }

    @Override
    public boolean updateBizJinjianInfoHuiKuan(JinjianInfo jinjianInfo) {
        if (null != jinjianInfo) {
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-回款确认");
            customerDongtaiService.save(customerDongtai);
            jinjianInfo.setIsHk("1");
            jinjianInfo.setHkTime(new Date());

            if (null == jinjianInfo.getServiceConfirmAmount()) {
                jinjianInfo.setServiceConfirmAmount(jinjianInfo.getServiceAmount());
            }


            // 回款确认 生成费用
            // 生成 资方结算/费用管理
            JinjianBill jinjianBill = null;
            jinjianBill = jinjianBillService.getByJinjianId(jinjianInfo.getId());
            if (null == jinjianBill) {
                jinjianBill = new JinjianBill();
                jinjianBill.setId(UUID.randomUUID().toString());
                jinjianBill.setIsNewRecord();
                jinjianBill.setJinjianId(jinjianInfo.getId());

                // 资方结算
                CapBill capBill = new CapBill();
                capBill.setJinjianId(jinjianInfo.getId());
                capBill.setCusName(jinjianInfo.getCustomerName());
                capBill.setCustomerId(jinjianInfo.getCustomerId());
                capBill.setSqAmount(jinjianInfo.getYxEdu()); //申请额度
                capBill.setFkAmount(jinjianInfo.getSjEdu()); // 放款额度
                capBill.setServiceName(jinjianInfo.getServcieUserName());
                capBill.setServiceId(jinjianInfo.getServcieUserId());
                capBill.setUserId(jinjianInfo.getUserId());
                capBill.setUserName(jinjianInfo.getUserName());
                capBill.setDeptId(jinjianInfo.getDeptId());
                capBill.setDeptName(jinjianInfo.getDeptName());
                capBill.setCompanyId(jinjianInfo.getCompanyId());
                capBill.setQdTime(jinjianInfo.getQiandanTime());
                capBill.setFkTime(jinjianInfo.getFkTime());
                capBill.setStatus("0");

                String qianyueProductId = jinjianInfo.getQianyueProductId();
                String qianyueProductName = jinjianInfo.getProductName();
                String orgType = jinjianInfo.getOrgType();
                if (null != qianyueProductId) {
                    if (null != jinjianInfo.getProductId() && jinjianInfo.getProductId().equals(qianyueProductId)) {
                        qianyueProductName = jinjianInfo.getProductName();
                        orgType = jinjianInfo.getOrgType();
                    }
                    if (null != jinjianInfo.getProductIdTwo() && jinjianInfo.getProductIdTwo().equals(qianyueProductId)) {
                        qianyueProductName = jinjianInfo.getProductNameTwo();
                        orgType = jinjianInfo.getOrgTypeTwo();
                    }
                    if (null != jinjianInfo.getProductIdThree() && jinjianInfo.getProductIdThree().equals(qianyueProductId)) {
                        qianyueProductName = jinjianInfo.getProductNameThree();
                        orgType = jinjianInfo.getOrgTypeThree();
                    }
                }

                capBill.setOrgType(orgType);
                capBill.setProductId(qianyueProductId);
                capBill.setProductName(qianyueProductName);
                capBillService.save(capBill);
            }
            jinjianBill.setCusName(jinjianInfo.getCustomerName());
            jinjianBill.setCustomerId(jinjianInfo.getCustomerId());
            jinjianBill.setStatus("0");
            jinjianBill.setSqAmount(jinjianInfo.getYxEdu()); //申请额度
            jinjianBill.setFkAmount(jinjianInfo.getSjEdu()); // 放款额度
            jinjianBill.setServiceAmount(jinjianInfo.getServiceAmount()); // 提交收入金额
            jinjianBill.setServiceName(jinjianInfo.getServcieUserName());
            jinjianBill.setServiceId(jinjianInfo.getServcieUserId());
            jinjianBill.setUserId(jinjianInfo.getUserId());
            jinjianBill.setUserName(jinjianInfo.getUserName());
            jinjianBill.setDeptId(jinjianInfo.getDeptId());
            jinjianBill.setQdTime(jinjianInfo.getQiandanTime());
            jinjianBill.setFkTime(jinjianInfo.getFkTime());
            jinjianBill.setCaiwuCheck("0");
            jinjianBill.setIsZuofei("0");
            jinjianBill.setServiceConfirmAmount(jinjianInfo.getServiceConfirmAmount());
            jinjianBill.setServiceKeyAmount(jinjianInfo.getServiceKeyAmount());
            jinjianBill.setServiceInsuranceAmount(jinjianInfo.getServiceInsuranceAmount());
            jinjianBill.setServiceDealAmount(jinjianInfo.getServiceDealAmount());
            jinjianBill.setServiceSignAmount(jinjianInfo.getServiceSignAmount());
            jinjianBill.setServiceGpsAmount(jinjianInfo.getServiceGpsAmount());
            jinjianBill.setServiceDiyaAmount(jinjianInfo.getServiceDiyaAmount());
            jinjianBill.setServiceJieyaAmount(jinjianInfo.getServiceJieyaAmount());
            jinjianBill.setServicePayAmount(jinjianInfo.getServicePayAmount());
            jinjianBill.setServiceOtherAmount(jinjianInfo.getServiceOtherAmount());
            jinjianBillService.save(jinjianBill);

            String xscbLogId = this.jinjianCleaning(jinjianInfo);
            if (StringUtils.isNotNull(xscbLogId)) {
                jinjianInfo.setXscbLogId(xscbLogId);
            }
            return this.edit(jinjianInfo);
        }
        return false;
    }


    @Override
    public boolean updateBizJinjianInfoZiLiaoBack(JinjianInfo jinjianInfo) {
        if (null != jinjianInfo) {
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-客户资料已寄回");
            customerDongtaiService.save(customerDongtai);
            return this.edit(jinjianInfo);
        }
        return false;
    }

    /**
     * 客服接单，下一步方案预审
     *
     * @param jinjianInfo
     * @return
     */
    @Override
    public boolean updateBizJinjianInfoKefuConfirm(JinjianInfo jinjianInfo) {
        if (null != jinjianInfo) {
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            customerDongtai.setContent(sysUser.getName() + "-客服接单");
            customerDongtaiService.save(customerDongtai);

            jinjianInfo.setServcieUserId(sysUser.getUserId());
            jinjianInfo.setServcieUserName(sysUser.getName());
            ToHomeUser toHomeUser = this.changeToHomeByJinjian(jinjianInfo, "2");

            // 客服接单@销售
            SysUser user = iSysUserService.get(jinjianInfo.getUserId());
            String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            String toHomeCompanyId = null;
            if (null != toHomeUser) {
                ToHome toHome = toHomeService.get(toHomeUser.getTohomeId());
                toHomeCompanyId = toHome.getToHomeCompanyId();
            }
            if (StringUtils.isNull(toHomeCompanyId)) {
                toHomeCompanyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
            }
            messageSendService.sendJinjianVxNewsToCompany(new String[]{user.getPhonenumber()}, "客服接单", new String[]{jinjianInfo.getCustomerName(), sdf}, toHomeCompanyId);
            return this.edit(jinjianInfo);
        }
        return false;
    }


    /**
     * 客服信审，下一步额度审批
     *
     * @param jinjianInfo
     * @return
     */
    @Override
    public boolean updateBizJinjianInfoKefuXinshen(JinjianInfo jinjianInfo) {
        if (null != jinjianInfo) {
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-客服资料信审");
            customerDongtaiService.save(customerDongtai);
            // 资料信审@销售
//            SysUser user = iSysUserService.get(jinjianInfo.getUserId());
//            String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//            messageSendService.sendJinjianVxNewsToCompany(user, "资料信审", new String[]{jinjianInfo.getCustomerName(), sdf});

            return this.edit(jinjianInfo);
        }
        return false;
    }

    @Override
    public boolean updateBizJinjianInfoYushen(JinjianInfo jinjianInfo) {
        if (null != jinjianInfo) {
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            String operate = "";
            if ("2".equals(jinjianInfo.getJinjianStatus())) {
                operate = "通过";
                this.changeToHomeByJinjian(jinjianInfo, "3");
            } else if ("-2".equals(jinjianInfo.getJinjianStatus())) {
                operate = "驳回";
                // 驳回后退回到客户进件 重新方案确认
                this.changeToHomeByJinjian(jinjianInfo, "0");
            }

            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-进件预审（" + operate + "）");
            customerDongtaiService.save(customerDongtai);

            // 进件预审@销售
//            SysUser user = iSysUserService.get(jinjianInfo.getUserId());
//            String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//            messageSendService.sendJinjianVxNewsToCompany(user, "进件预审", new String[]{jinjianInfo.getCustomerName(), operate, sdf});

            return this.edit(jinjianInfo);
        }
        return false;
    }


    /**
     * 销售费用确认，下一步客服签约
     *
     * @param jinjianInfo
     * @return
     */
    @Override
    public boolean updateBizJinjianInfoConfirmBill(JinjianInfo jinjianInfo) {
        if (null != jinjianInfo) {
            String operate = "";
            String disAgreeRemark = "";
            if ("6".equals(jinjianInfo.getJinjianStatus())) {
                operate = "接受";
            } else if ("-6".equals(jinjianInfo.getJinjianStatus())) {
                operate = "拒绝";
                disAgreeRemark = jinjianInfo.getServiceAmountRemark();
            }
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-费用确认（" + operate + "）");
            customerDongtaiService.save(customerDongtai);

            // 费用确认@所有人
            ToHomeUser toHomeUser = this.changeToHomeByJinjian(jinjianInfo, "4");
            String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());


//            String toHomeCompanyId = null;
//            if (null != toHomeUser) {
//                ToHome toHome = toHomeService.get(toHomeUser.getTohomeId());
//                toHomeCompanyId = toHome.getToHomeCompanyId();
//            }
//            if (StringUtils.isNull(toHomeCompanyId)) {
//                toHomeCompanyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
//            }
//            messageSendService.sendJinjianVxNewsToCompany(null, "费用确认", new String[]{jinjianInfo.getCustomerName(), operate, disAgreeRemark, sdf}, toHomeCompanyId);

            return this.edit(jinjianInfo);
        }
        return false;
    }

    @Override
    public boolean updateBizJinjianInfoConfirmInterest(JinjianInfo jinjianInfo) {
        if (null != jinjianInfo) {
            String operate = "";
            String disAgreeRemark = "";
            if ("3".equals(jinjianInfo.getJinjianStatus())) {
                operate = "接受";
            } else if ("-3".equals(jinjianInfo.getJinjianStatus())) {
                operate = "拒绝";
                disAgreeRemark = jinjianInfo.getRemark();
            }
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-费率确认（" + operate + "）");
            customerDongtaiService.save(customerDongtai);
            // 费率确认@所有人
            String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            ToHomeUser toHomeUser = this.changeToHomeByJinjian(jinjianInfo, "4");

//            String toHomeCompanyId = null;
//            if (null != toHomeUser) {
//                ToHome toHome = toHomeService.get(toHomeUser.getTohomeId());
//                toHomeCompanyId = toHome.getToHomeCompanyId();
//            }
//            if (StringUtils.isNull(toHomeCompanyId)) {
//                toHomeCompanyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
//            }
//            messageSendService.sendJinjianVxNewsToCompany(null, "费率确认", new String[]{jinjianInfo.getCustomerName(), operate, disAgreeRemark, sdf}, toHomeCompanyId);

            return this.edit(jinjianInfo);
        }
        return false;
    }

    @Override
    public boolean updateBizJinjianInfoConfirmAgain(JinjianInfo jinjianInfo) {
        if (null != jinjianInfo) {
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "重新确认方案");
            customerDongtaiService.save(customerDongtai);
            return this.edit(jinjianInfo);
        }
        return false;
    }


    private ToHomeUser changeToHomeByJinjian(JinjianInfo jinjianInfo, String status) {
        ToHomeUser toHomeUserParam = new ToHomeUser();
        toHomeUserParam.setCustomerId(jinjianInfo.getCustomerId());
        toHomeUserParam.setJinjianId(jinjianInfo.getId());
        List<ToHomeUser> toHomeUserList = toHomeUserService.findList(toHomeUserParam);
        if (null != toHomeUserList && !toHomeUserList.isEmpty()) {
            ToHomeUser toHomeUser = toHomeUserList.get(0);
            toHomeUser.setYushenStatus(status);
            toHomeUserService.save(toHomeUser);
            return toHomeUser;
        }
        return null;
    }


    /**
     * 签约驳回，驳回到费用确认
     *
     * @param jinjianInfo
     * @return
     */
    @Override
    public boolean updateBizJinjianInfoQianYueRefuse(JinjianInfo jinjianInfo) {
        if (null != jinjianInfo) {
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-签约驳回");
            customerDongtaiService.save(customerDongtai);

            jinjianInfo.setQianyueProductId(null);
            return this.edit(jinjianInfo);
        }
        return false;
    }

    @Override
    public JinjianInfo findOneJinjianCleaning() {
        return mapper.findOneJinjianCleaning();
    }


    @Override
    @Transactional(readOnly = false)
    public String jinjianCleaning(JinjianInfo jinjianInfo) {
        try {
            if (null != jinjianInfo) {
                JinjianBill jinjianBill = jinjianBillService.getByJinjianId(jinjianInfo.getId());
                Customer customer = customerService.get(jinjianInfo.getCustomerId());

                XiansuoChengbenLog xiansuoChengbenLogExist = null;
                if (StringUtils.isNotNull(jinjianInfo.getXscbLogId())) {
                    xiansuoChengbenLogExist = xiansuoChengbenLogService.get(jinjianInfo.getXscbLogId());
                } else {
                    XiansuoChengbenLog xiansuoChengbenLog = new XiansuoChengbenLog();
                    xiansuoChengbenLog.setCustomerId(jinjianInfo.getCustomerId());
                    xiansuoChengbenLog.setLaiyuan(jinjianInfo.getLaiyuan());
                    xiansuoChengbenLog.setCreateTime(jinjianInfo.getCreateTime());
                    xiansuoChengbenLogExist = xiansuoChengbenLogService.findOneChengjiaoLasted(xiansuoChengbenLog);
                }
                boolean isSuccess = false;
                if (null != xiansuoChengbenLogExist) {
                    xiansuoChengbenLogExist.setIsCj(1);
                    xiansuoChengbenLogExist.setCjTime(jinjianInfo.getCjTime());
                    xiansuoChengbenLogExist.setJinjianId(jinjianInfo.getId());
                    if (null != jinjianBill) {
                        xiansuoChengbenLogExist.setIsHk(1);
                        xiansuoChengbenLogExist.setHkTime(jinjianBill.getCreateTime());
                        xiansuoChengbenLogExist.setJinjianBillId(jinjianBill.getId());
                        xiansuoChengbenLogExist.setServiceAmountCheck(jinjianBill.getServiceAmountCheck());
                    }
                    isSuccess = xiansuoChengbenLogService.saveByCityAndLaiyuan(xiansuoChengbenLogExist);
                } else {
                    String uuid = UUID.randomUUID().toString();
                    xiansuoChengbenLogExist = new XiansuoChengbenLog();
                    xiansuoChengbenLogExist.setStatus("0");//数清清洗标记
                    xiansuoChengbenLogExist.setIsNewRecord();
                    xiansuoChengbenLogExist.setId(uuid);
                    xiansuoChengbenLogExist.setCreateTime(customer.getReceiveTime());
                    xiansuoChengbenLogExist.setCityName(customer.getCityName());
                    xiansuoChengbenLogExist.setLaiyuan(jinjianInfo.getLaiyuan());
                    String dictLabel = sysDictDataService.selectDictLabel("bus_type", jinjianInfo.getLaiyuan());
                    if (null != dictLabel) {
                        xiansuoChengbenLogExist.setLaiyuanType("1");
                    } else {
                        xiansuoChengbenLogExist.setLaiyuanType("2");
                    }
                    xiansuoChengbenLogExist.setCustomerId(jinjianInfo.getCustomerId());
                    xiansuoChengbenLogExist.setIsRep(0);
                    xiansuoChengbenLogExist.setIsSum(0);// 历史数据的不计算成本 不统计
                    xiansuoChengbenLogExist.setIsCj(1);
                    xiansuoChengbenLogExist.setCjTime(jinjianInfo.getCjTime());
                    xiansuoChengbenLogExist.setJinjianId(jinjianInfo.getId());
                    if (null != jinjianBill) {
                        xiansuoChengbenLogExist.setIsHk(1);
                        xiansuoChengbenLogExist.setHkTime(jinjianBill.getCreateTime());
                        xiansuoChengbenLogExist.setJinjianBillId(jinjianBill.getId());
                        xiansuoChengbenLogExist.setServiceAmountCheck(jinjianBill.getServiceAmountCheck());
                    }

                    xiansuoChengbenLogExist.setUserId(customer.getUserId());
                    xiansuoChengbenLogExist.setUserName(customer.getUserName());
                    xiansuoChengbenLogExist.setDeptId(customer.getDeptId());
                    xiansuoChengbenLogExist.setDeptName(customer.getDeptName());
                    xiansuoChengbenLogExist.setCompanyId(customer.getCompanyId());
                    xiansuoChengbenLogExist.setCompanyName(customer.getCompanyName());
                    isSuccess = xiansuoChengbenLogService.saveByCityAndLaiyuan(xiansuoChengbenLogExist);
                }
                if (isSuccess) {
                    return xiansuoChengbenLogExist.getId();
                }
            }
        } catch (Exception e) {
            //throw new RuntimeException(e);
            log.error("数据清洗{}", e.getLocalizedMessage());
        }
        return null;
    }

    @Override
    @Transactional(readOnly = false)
    public boolean updateBizJinjianInfoHuiKuanRefuse(JinjianInfo jinjianInfo) {
        if (null != jinjianInfo) {
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-回款退回");
            customerDongtaiService.save(customerDongtai);
            jinjianInfo.setIsFk("0");
            jinjianInfo.setCjTime(null);

            //删除还款信息
            LoanBill loanBillParam = new LoanBill();
            loanBillParam.setCustomerId(jinjianInfo.getCustomerId());
            loanBillParam.setJinjianId(jinjianInfo.getId());
            LoanBill loanBill = loanBillService.findOne(loanBillParam);
            if (null != loanBill) {
                loanBillService.deleteById(loanBill.getId());
            }

            //删除成交信息
            XiansuoChengbenLog xiansuoChengbenLog = xiansuoChengbenLogService.get(jinjianInfo.getXscbLogId());
            if (null != xiansuoChengbenLog) {
                xiansuoChengbenLog.setIsCj(0);
                xiansuoChengbenLog.setCjTime(null);
                xiansuoChengbenLogService.save(xiansuoChengbenLog);
            }
            return this.edit(jinjianInfo);
        }
        return false;
    }


}
